package com.fast.fast.common.core.advice;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.util.Date;

/**
 * Controller增强类
 *
 * @author lyf
 * @date 2022/01/01 00:00 周六
 **/
@ControllerAdvice
public class MyAdvice {

    /**
     * 将前端传递过来的字符串，自动转化为相应类型
     *
     * @param binder
     */
    @InitBinder
    public void globalInitBinder(WebDataBinder binder) {
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @SneakyThrows
            @Override
            public void setAsText(String text) {
                setValue(DateUtil.parse(text));
            }
        });
        // JSONObject 类型转换
        binder.registerCustomEditor(JSONObject.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(JSON.parseObject(text));
            }
        });
        // JSONArray 类型转换
        binder.registerCustomEditor(JSONArray.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(JSON.parseArray(text));
            }
        });
    }

}
